import asyncio
import urllib.parse
from typing import Optional
from datetime import datetime
from filter_video import FilterVideo
from get_tiktok_url import TiktokUrl
from playwright.async_api import async_playwright
import requests
import os
import re


class VideoDownloader:
    def __init__(self, save_path: str = "videos"):
        self.save_path = save_path
        self.chromium_path = "/usr/bin/chromium"  # 指定自定义Chromium路径
        self.create_save_directory()

    def create_save_directory(self):
        if not os.path.exists(self.save_path):
            os.makedirs(self.save_path)

    def build_dlpanda_url(self, tiktok_url: str) -> str:
        """
        将 TikTok 原始视频地址拼接成 dlpanda 的解析地址
        """
        encoded_url = urllib.parse.quote(tiktok_url, safe="")
        return f"https://dlpanda.com/?url={encoded_url}"

    def get_filename(self, platform: str, custom_name: Optional[str] = None) -> str:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        prefix = custom_name or platform
        safe_name = re.sub(r'[\\/:"*?<>|]+', "_", prefix)
        return f"{safe_name}_{timestamp}.mp4"

    async def download_video(
        self, url: str, custom_name: Optional[str] = None
    ) -> Optional[str]:
        platform = FilterVideo.detect_platform(url)
        if not platform:
            print("❌ Unsupported URL/platform.")
            return None

        # 获取视频源地址
        video_src = await TiktokUrl.from_dlpanda(url)
        if not video_src:
            raise ValueError("未找到视频地址，请检查 TikTok URL 是否有效")

        if video_src.startswith("//"):
            video_url = "https:" + video_src
        else:
            video_url = video_src

        print(f"[INFO] 解析到视频地址: {video_url}")
        filename = self.get_filename(video_url, custom_name)
        output_path = os.path.join(self.save_path, filename)

        # 下载视频
        print(f"[INFO] 正在下载视频到 {output_path}")

        headers = {"User-Agent": "Mozilla/5.0"}
        with requests.get(video_url, headers=headers, stream=True) as r:
            r.raise_for_status()
            with open(output_path, "wb") as f:
                for chunk in r.iter_content(chunk_size=8192):
                    f.write(chunk)

        print(f"[SUCCESS] 视频下载完成: {output_path}")
        return output_path
